<?php

class Silk_Mapi_Model_Api2_Contacts_Rest extends Silk_Mapi_Model_Api2_Contacts
{
    const XML_PATH_EMAIL_RECIPIENT = 'contacts/email/recipient_email';
    const XML_PATH_EMAIL_SENDER = 'contacts/email/sender_email_identity';
    const XML_PATH_EMAIL_TEMPLATE = 'contacts/email/email_template';
    const XML_PATH_ENABLED = 'contacts/contacts/enabled';

    protected function _create(array $post)
    {
        if ($post && $this->getParam('comment') && $this->getParam('name')) {
            $translate = Mage::getSingleton('core/translate');
            /* @var $translate Mage_Core_Model_Translate */
            $translate->setTranslateInline(false);
            try {
                $postObject = new Varien_Object();
                $postObject->setData($post);

                $error = false;

                if (!Zend_Validate::is(trim($post['name']), 'NotEmpty')) {
                    $error = true;
                }

                if (!Zend_Validate::is(trim($post['comment']), 'NotEmpty')) {
                    $error = true;
                }

                // if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
                //     $error = true;
                // }


                if ($error) {
                    throw new Exception();
                }
                $mailTemplate = Mage::getModel('core/email_template');
                /* @var $mailTemplate Mage_Core_Model_Email_Template */
                $mailTemplate->setDesignConfig(array('area' => 'frontend'))
                    ->setReplyTo($post['mobile'])
                    ->sendTransactional(
                        Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE),
                        Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
                        Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
                        null,
                        array('data' => $postObject)
                    );

                if (!$mailTemplate->getSentSuccess()) {
                    throw new Exception();
                }

                $translate->setTranslateInline(true);

                return array();
            } catch (Exception $e) {
                $translate->setTranslateInline(true);

                $this->_critical("提交失败请稍后尝试！" . $e->getMessage(), Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
            }

        } else {
            $this->_critical("请填写数据！", Mage_Api2_Model_Resource::ERROR_CONTACTS_NO_CONTENT);
        }
    }
}